package cn.elead.chaos.sso.server.web.monitor.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.eventbus.Subscribe;

import cn.elead.chaos.async.BaseSubscriber;
import cn.elead.chaos.async.EventBusRegister;
import cn.elead.chaos.core.converter.Convert;
import cn.elead.chaos.sso.server.web.monitor.domain.SysLogininfor;
import cn.elead.chaos.sso.server.web.monitor.mapper.SysLogininforMapper;
import cn.elead.chaos.sso.server.web.monitor.service.ISysLogininforService;
import cn.elead.chaos.sso.server.web.system.domain.SysDept;
import cn.elead.chaos.sso.server.web.system.domain.SysUser;
import cn.elead.chaos.sso.server.web.system.mapper.SysDeptMapper;
import cn.elead.chaos.sso.server.web.system.mapper.SysUserMapper;
import cn.hutool.core.util.ObjectUtil;

/**
 * 系统访问日志情况信息 服务层处理
 * 
 * @author luopeng
 */
@Service
@EventBusRegister
public class SysLogininforServiceImpl implements ISysLogininforService, BaseSubscriber<SysLogininfor>
{

    @Autowired
    private SysLogininforMapper logininforMapper;
    
    @Autowired
    private SysUserMapper sysUserMapper;
    
    @Autowired
    private SysDeptMapper sysDeptMapper;

    /**
     * 新增系统登录日志
     * 
     * @param logininfor 访问日志对象
     */
    @Override
    public void insertLogininfor(SysLogininfor logininfor)
    {
        logininforMapper.insertLogininfor(logininfor);
    }

    /**
     * 查询系统登录日志集合
     * 
     * @param logininfor 访问日志对象
     * @return 登录记录集合
     */
    @Override
    public List<SysLogininfor> selectLogininforList(SysLogininfor logininfor)
    {
        return logininforMapper.selectLogininforList(logininfor);
    }
    
    /**
     * 查询在线用户
     * @param userOnline
     * @return
     */
	public List<SysLogininfor> selectLogininBySessions(SysLogininfor userOnline){
		return logininforMapper.selectLogininBySessions(userOnline);
	}

    /**
     * 批量删除系统登录日志
     * 
     * @param ids 需要删除的数据
     * @return
     */
    @Override
    public int deleteLogininforByIds(String ids)
    {
        return logininforMapper.deleteLogininforByIds(Convert.toStrArray(ids));
    }

    /**
     * 清空系统登录日志
     */
    @Override
    public void cleanLogininfor()
    {
        logininforMapper.cleanLogininfor();
    }
    

	@Override
	@Subscribe
	@Transactional
	public void subscribe(SysLogininfor logininfor) {
		SysUser sysUser = sysUserMapper.selectUserByLoginName(logininfor.getLoginName());
		if(ObjectUtil.isNotNull(sysUser)) {
			SysDept sysDept = sysDeptMapper.selectDeptById(sysUser.getDeptId());
			if(ObjectUtil.isNotNull(sysDept)) {
				logininfor.setDeptName(sysDept.getDeptName());
			}
		}
		insertLogininfor(logininfor);
	}
}
